<template>
  <div class="setting">
    <el-row type="flex" justify="center">
      <el-col :span="14">
        <el-form ref="userFormRef" :model="userForm" label-width="80px" :rules="userFormRules">
          <el-form-item label="用户头像">
            <el-upload
              :class="{'avatar-uploader': true, 'none-border': userForm.avatar!==undefined}"
              :action="baseUrl + '/upload/single/1'"
              :headers="{Authorization: token}"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :disabled="!isEdit"
            >
              <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-col :span="18">
              <el-input v-model="userForm.username" :readonly="!isEdit"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-col :span="18">
              <el-input v-model="userForm.realName" :readonly="!isEdit"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-col :span="18">
              <el-input v-model="userForm.phone" :readonly="!isEdit"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitEditForm" v-if="isEdit">保存修改</el-button>
            <el-button @click="isEdit = false" v-if="isEdit">取消</el-button>
            <el-button @click="isEdit = true" v-else>编辑</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getUserByIdApi, updateUserApi } from "@/api/user";
import { base_url } from "@/api/apiConfig";
export default {
  name: "Setting",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        return callback();
      } else {
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      }
    };
    return {
      userForm: {
        id: -1,
        username: undefined,
        realName: undefined,
        phone: undefined,
        avatar: undefined,
      },
      isEdit: false,
      baseUrl: base_url,
      userFormRules: {
        username: [
          { required: true, message: "请填写用户名", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请填写真实姓名", trigger: "blur" },
        ],
        phone: [{ validator: validatePhone, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getUserById();
  },
  computed: {
    token() {
      return this.$store.state.userModule.token;
    },
    currId() {
      return this.$store.state.userModule.user.id;
    },
  },
  methods: {
    async getUserById() {
      const { code, data } = await getUserByIdApi(this.currId);
      if (code !== 200) return;
      this.userForm = data;
    },
    handleAvatarSuccess(res) {
      this.userForm.avatar = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submitEditForm() {
      this.$refs.userFormRef.validate(async (valid) => {
        if (!valid) return;
        let { code, data } = await updateUserApi(this.userForm);
        if (code !== 200) return;
        this.userForm = data;
        this.isEdit = false;
        this.$store.dispatch("UpdateUser", data);
        this.$message.success("更新用户成功");
      });
    },
  },
};
</script>

<style scoped lang="scss">
.setting {
  margin-top: 20px;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
.none-border .el-upload {
  border: none;
}
</style>
